package consys.social.memcached.service.spymemcached;

import consys.social.core.bo.WallPost;
import consys.social.core.bo.WallPostType;
import consys.social.core.service.DiscussionPostTranscoder;
import consys.social.core.service.SocialUtils;
import java.text.ParseException;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import net.spy.memcached.CachedData;
import net.spy.memcached.transcoders.Transcoder;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * Transcoder of WallPost to be saved/loaded into/from memcached
 *
 * @author Petr Kunc
 */
public class WallPostTranscoder implements Transcoder<WallPost> {
    private final int holdDiscPosts = Integer.parseInt(ResourceBundle.getBundle("social").getString("post.discussion.holdInMem"));

    @Override
    public boolean asyncDecode(CachedData cd) {
        return false;
    }

    @Override
    public CachedData encode(WallPost t) {
        String data = t.getText() + ">"
                + SocialUtils.dateToString(t.getDate()) + ">"
                + t.getType().getTypeNumber() + ">"
                + t.getLikesCount() + ">"
                + t.getDiscussionCount();
        int saved = 0;
        for (int i = t.getDiscussion().size() - 1; i >= 0; i--) {
            if (saved >= holdDiscPosts) {
                break;
            }
            data += ">" + new DiscussionPostTranscoder().encodeToString(t.getDiscussion().get(i));
            saved++;
        }
        return new CachedData(0, data.getBytes(), getMaxSize());
    }

    @Override
    public WallPost decode(CachedData cd) {
        String serialized = Bytes.toString(cd.getData());
        WallPost wp = new WallPost();
        String[] parts = StringUtils.split(serialized, '>');
        wp.setText(parts[0]);
        try {
            wp.setDate(SocialUtils.stringToDate(parts[1]));
        } catch (ParseException ex) {
            //this should never happen
        }
        wp.setType(new WallPostType(Integer.parseInt(parts[2])));
        wp.setLikesCount(Integer.parseInt(parts[3]));
        wp.setDiscussionCount(Integer.parseInt(parts[4]));
        for(int i = 5; i < parts.length; i++) {
            wp.addDiscussionPost(new DiscussionPostTranscoder().decodeFromString(parts[i]));
        }
        return wp;
    }

    @Override
    public int getMaxSize() {
        return CachedData.MAX_SIZE;
    }
}